package com.service.single.service.impl;

import cn.hutool.core.io.file.FileReader;
import com.service.single.entity.FileInfo;
import com.service.single.service.ElasticsearchService;
import com.service.single.service.FileParseService;
import lombok.extern.slf4j.Slf4j;
import org.apache.pdfbox.io.RandomAccessBuffer;
import org.apache.pdfbox.pdfparser.PDFParser;
import org.apache.pdfbox.pdmodel.PDDocument;
import org.apache.pdfbox.text.PDFTextStripper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.io.BufferedInputStream;

/**
 * @Author: 一休
 * @DateTime: 2022/11/2 16:00
 */
@Slf4j
@Service
public class PdfParseServiceImpl implements FileParseService {

    @Autowired
    private ElasticsearchService elasticsearchService;

    @Override
    public void fileParse(FileInfo fileInfo) {
        Integer fileType = fileInfo.getFileType();
        String filePath = fileInfo.getFilePath();
        if (fileType != 3) {
            return;
        }
        FileReader fileReader = new FileReader(filePath);
        BufferedInputStream inputStream = fileReader.getInputStream();
        try {
            RandomAccessBuffer buffer = new RandomAccessBuffer(inputStream);
            PDFParser pdfParser = new PDFParser(buffer);
            pdfParser.parse();
            PDDocument document = pdfParser.getPDDocument();
            // 获取页码
            int pages = document.getNumberOfPages();
            PDFTextStripper stripper = new PDFTextStripper();
            // 设置按顺序输出
            stripper.setSortByPosition(true);
            stripper.setStartPage(1);
            stripper.setEndPage(pages);
            String text = stripper.getText(document);
            document.close();
            StringBuilder builder = new StringBuilder(text);
            elasticsearchService.insertFileContent(fileInfo, builder);
        } catch (Exception e) {
            log.error("pdf文件解析异常 {}", e.getMessage());
        }
    }
}
